<template>
  <div>
    <h2>井子棋</h2>
    <p>
      先手：
      <label for="O">O</label>
      <input type="radio" id="O" v-model="first" value="O" />
      &nbsp;&nbsp;&nbsp;&nbsp;
      <label for="X">X</label>
      <input type="radio" id="X" v-model="first" value="X" />
    </p>
    <p>
      <button @click="resetGame">重新开始</button>
    </p>
    <div class="pieceBox">
      <Piece
        @drop="drop"
        :piece="piece"
        :num="index"
        v-for="(piece, index) in pieces"
        :key="index"
      ></Piece>
    </div>
  </div>
</template>

<script>
import Piece from "@/components/Piece.vue";
export default {
  name: "Game",
  components: {
    Piece,
  },
  data() {
    return {
      pieces: [],
      first: "X",
    };
  },
  created() {
    this.pieces = new Array(9);
    // this.pieces[5] = 'X'
  },
  methods: {
    resetGame() {
      this.pieces = new Array(9);
      this.first = 'X';
    },
    drop(num) {
      console.log("下棋", num);
      const temp = this.pieces.slice();
      temp[num] = this.first;
      this.pieces = temp;
      this.first = this.first === "O" ? "X" : "O";
      const winner =  this.isWin(this.pieces);
      this.$nextTick(()=>{
        if(winner){
            alert(`${winner}'胜利了`);
            this.resetGame();
        }
      })

    },
    isWin(squares) {
        const lines = [
          [0, 1, 2],
          [3, 4, 5],
          [6, 7, 8],
          [0, 3, 6],
          [1, 4, 7],
          [2, 5, 8],
          [0, 4, 8],
          [2, 4, 6],
        ];
        for (let i = 0; i < lines.length; i++) {
          const [a, b, c] = lines[i];
          if (
            squares[a] &&
            squares[a] === squares[b] &&
            squares[a] === squares[c]
          ) {
            return squares[a];
          }
        }
        return null;
      }
    },
};
</script>

<style lang="scss" scoped>
.pieceBox {
  width: 300px;
  height: 300px;
  border: 1px solid #000;
  display: flex;
  flex-wrap: wrap;
}
</style>